package com.springcloud.sc.ucpv5.client.module.map.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.springcloud.sc.ucpv5.client.module.map.data.GeoPositionPoint;
import com.springcloud.sc.ucpv5.client.module.map.data.data_address.GpsAddressData;

@Component
public class MapAddressUtil {
	private static final Logger logger = LoggerFactory.getLogger(MapAddressUtil.class);

	public static String getAddressDesc_Name(double latitude, double longitude) {
		GpsAddressData addressData = getAddressDesc(latitude, longitude);
		if (addressData.error.equals("")) {
			return addressData.name;
		}
		return "";
	}

	public static GpsAddressData getAddressDesc(double latitude, double longitude) {

		// 默认从百度获取
		return getAddressDesc_BaiDu(latitude, longitude);
	}

	/**
	 * 百度地图通过定位反查详细地址
	 * 
	 * @param latitude
	 * @param longitude
	 * @return
	 */
	public static GpsAddressData getAddressDesc_BaiDu(double latitude, double longitude) {
		// wsy 20181114 通过百度获取地址
		GeoPositionPoint geoPosition_1 = GpsChangeUtil.gcj_encrypt(latitude, longitude);
		GeoPositionPoint geoPosition_2 = GpsChangeUtil.bd_encrypt(geoPosition_1.getLatitude(), geoPosition_1.getLongitude());

		String location = geoPosition_2.getLatitude() + "," + geoPosition_2.getLongitude();
		String key = "0428f539a07d41cd66cbf07cb83dd8cf";
		String url = "http://api.map.baidu.com/geocoder/v2/?ak=" + key + "&location=" + location + "&output=json&pois=1";


		String json = loadJSON(url);

		GpsAddressData addresData = new GpsAddressData();
		try {
			if (json.length() > 0) {
				JSONObject obj = JSONObject.parseObject(json);
				String return_code = obj.get("status").toString();
				if (return_code.equals("0")) {
					JSONObject result = obj.getJSONObject("result");
					addresData.addr = result.getString("formatted_address");
					addresData.name = result.getString("sematic_description");

					// 百度转标准
					GeoPositionPoint geoPosition_1_1 = GpsChangeUtil.bd_decrypt(result.getJSONObject("location").getDouble("lat"), result.getJSONObject("location").getDouble("lng"));
					GeoPositionPoint geoPosition_2_1 = GpsChangeUtil.gcj_decrypt(geoPosition_1_1.getLatitude(), geoPosition_1_1.getLongitude());
					addresData.lat = geoPosition_2_1.getLatitude();
					addresData.lng = geoPosition_2_1.getLongitude();

					try {
						// 下级位置节点
						JSONArray poins = result.getJSONArray("pois");
						for (int i = 0; i < poins.size(); i++) {
							GpsAddressData point = new GpsAddressData();
							point.addr = poins.getJSONObject(i).getString("addr");
							point.name = poins.getJSONObject(i).getString("name");
							point.lat = poins.getJSONObject(i).getJSONObject("point").getDouble("y");
							point.lng = poins.getJSONObject(i).getJSONObject("point").getDouble("x");

							// 百度转标准
							geoPosition_1_1 = GpsChangeUtil.bd_decrypt(poins.getJSONObject(i).getJSONObject("point").getDouble("y"), poins.getJSONObject(i).getJSONObject("point").getDouble("x"));
							geoPosition_2_1 = GpsChangeUtil.gcj_decrypt(geoPosition_1_1.getLatitude(), geoPosition_1_1.getLongitude());
							point.lat = geoPosition_2_1.getLatitude();
							point.lng = geoPosition_2_1.getLongitude();
							addresData.pointList.add(point);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else if (return_code.equals("310")) {
					addresData.error = "请求参数信息有误";
				} else if (return_code.equals("311")) {
					addresData.error = "Key格式错误";
				} else if (return_code.equals("306")) {
					addresData.error = "请求有护持信息请检查字符串";
				} else if (return_code.equals("110")) {
					addresData.error = "请求来源未被授权";
				}
			} else {
				addresData.error = "未获取取到数据";
			}
		} catch (Exception ex) {
			addresData.error = "未获取取到数据:" + ex.getMessage();
		}
		return addresData;
	}

	/**
	 * 腾讯地图通过定位反查详细地址
	 * 
	 * @param latitude
	 * @param longitude
	 * @return
	 */
	public static GpsAddressData getAddressDesc_TenXun(double latitude, double longitude) {
		String location = latitude + "," + longitude;
		String url = "http://apis.map.qq.com/ws/geocoder/v1/?location=" + location + "&key=AZLBZ-FD7KK-HNBJV-ABCI2-GYLJV-D6FGC&get_poi=1";
		String json = loadJSON(url);

		GpsAddressData addresData = new GpsAddressData();
		try {
			if (json.length() > 0) {
				JSONObject obj = JSONObject.parseObject(json);
				String return_code = obj.get("status").toString();
				if (return_code.equals("0")) {
					JSONObject result = obj.getJSONObject("result");
					addresData.addr = result.getString("formatted_address");
					addresData.name = result.getString("sematic_description");
					addresData.lat = result.getJSONObject("location").getDouble("lat");
					addresData.lng = result.getJSONObject("location").getDouble("lng");

					try {
						// 下级位置节点
						JSONArray poins = result.getJSONArray("poins");
						for (int i = 0; i < poins.size(); i++) {
							GpsAddressData point = new GpsAddressData();
							point.addr = poins.getJSONObject(i).getString("addr");
							point.name = result.getString("name");
							point.lat = result.getJSONObject("point").getDouble("y");
							point.lng = result.getJSONObject("point").getDouble("x");
							addresData.pointList.add(point);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else if (return_code.equals("310")) {
					addresData.error = "请求参数信息有误";
				} else if (return_code.equals("311")) {
					addresData.error = "Key格式错误";
				} else if (return_code.equals("306")) {
					addresData.error = "请求有护持信息请检查字符串";
				} else if (return_code.equals("110")) {
					addresData.error = "请求来源未被授权";
				}
			} else {
				addresData.error = "未获取取到数据";
			}
		} catch (Exception ex) {
			addresData.error = "未获取取到数据:" + ex.getMessage();
		}
		return addresData;
	}

	/**
	 * 获取是去名
	 * 
	 * @param latitude
	 * @param longitude
	 * @return
	 */
	public static Map<String, String> getCity(String latitude, String longitude) {
		Map<String, String> map = new HashMap<String, String>();
		String location = latitude + "," + longitude;
		String url = "http://apis.map.qq.com/ws/geocoder/v1/?location=" + location + "&key=AZLBZ-FD7KK-HNBJV-ABCI2-GYLJV-D6FGC&get_poi=1";
		String json = loadJSON(url);
		try {
			if (json.length() > 0) {
				JSONObject obj = JSONObject.parseObject(json);
				String return_code = obj.get("status").toString();
				if (return_code.equals("0")) {
					String city = obj.getJSONObject("result").getJSONObject("address_component").getString("city");
					map.put("result", "ok");
					map.put("city", city);
				} else if (return_code.equals("310")) {
					map.put("result", "no");
					String msg = "请求参数信息有误";
					logger.debug("310-----------" + msg);
					map.put("msg", msg);
				} else if (return_code.equals("311")) {
					map.put("result", "no");
					String msg = "Key格式错误";
					logger.debug("311-----------" + msg);
					map.put("msg", msg);
				} else if (return_code.equals("306")) {
					map.put("result", "no");
					String msg = "请求有护持信息请检查字符串";
					logger.debug("306-----------" + msg);
					map.put("msg", msg);
				} else if (return_code.equals("110")) {
					map.put("result", "no");
					String msg = "请求来源未被授权";
					logger.debug("110-----------" + msg);
					map.put("msg", msg);
				}
			} else {
				map.put("result", "no");
				map.put("msg", "未获取取到数据");
			}
		} catch (Exception ex) {
			ex.printStackTrace();

			map.put("result", "no");
		}
		return map;
	}

	public static String loadJSON(String url) {
		StringBuilder json = new StringBuilder();
		try {
			URL oracle = new URL(url);
			HttpURLConnection yc = (HttpURLConnection) oracle.openConnection();
			yc.setConnectTimeout(1000);
			yc.setReadTimeout(3000);
			BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				json.append(inputLine);
			}
			in.close();
		} catch (MalformedURLException e) {
		} catch (IOException e) {
		}
		return json.toString();
	}

	// java根据经纬度获取地址
	public static String getAddressLocation(String log, String lat) {
		// lat 39.97646
		// log 116.3039
		String add = getAddressLocationUrl(log, lat);
		JSONObject jsonObject = JSONObject.parseObject(add);
		JSONArray jsonArray = jsonObject.getJSONArray(jsonObject.getString("addrList"));
		JSONObject j_2 = JSONObject.parseObject(jsonArray.get(0).toString());
		String allAdd = j_2.getString("admName");
		String arr[] = allAdd.split(",");
		System.out.println("省：" + arr[0] + "\n市：" + arr[1] + "\n区：" + arr[2]);
		return "省：" + arr[0] + "\n市：" + arr[1] + "\n区：" + arr[2];

	}

	private static String getAddressLocationUrl(String log, String lat) {
		// lat 小 log 大
		// 参数解释: 纬度,经度 type 001 (100代表道路，010代表POI，001代表门址，111可以同时显示前三项)
		String urlString = "http://gc.ditu.aliyun.com/regeocoding?l=" + lat + "," + log + "&type=010";
		JSONObject salerJson = JSONObject.parseObject(getAddressLocationUrl(urlString));
		JSONObject jsonData = JSONObject.parseObject(salerJson.toJSONString());
		/*
		 * JSONArray fileItemsjson =
		 * JSONArray.fromObject(jsonData.get("addrList").toString());
		 * System.out.println("地区"+fileItemsjson); JSONObject job =
		 * fileItemsjson.getJSONObject(0);
		 */
		return jsonData.toString();

	}

	private static String getAddressLocationUrl(String url) {
		String resData = null;
		StringBuffer s = new StringBuffer();
		BufferedReader bReader = null;
		try {
			// 114.55.248.182
			URL urlWeb = new URL(url);
			URLConnection connection = urlWeb.openConnection();
			bReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
			while (null != (resData = bReader.readLine())) {
				s.append(resData);
			}
			bReader.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return s.toString();
	}

}
